import React, { useEffect, useState } from 'react';
import { Card, Table, Button, Space, Input, Form, Select, message, Tag } from 'antd';
import { useNavigate } from 'react-router-dom';
import type { ColumnsType } from 'antd/es/table';
import { getAssetsList, AssetInfo, AssetsListParams } from '../../../services/assets';
import './styles.css';

const { Option } = Select;

const AssetsList: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<AssetInfo[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 获取资源列表数据
  const fetchAssetsList = async (params: AssetsListParams = {}) => {
    try {
      setLoading(true);
      const { current = 1, size = 10, ...restParams } = params;
      const response = await getAssetsList({
        current,
        size,
        ...restParams,
      });
      setData(response.records);
      setPagination({
        current: response.current,
        pageSize: response.size,
        total: response.total,
      });
    } catch (error) {
      message.error('获取资源列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 首次加载
  useEffect(() => {
    fetchAssetsList();
  }, []);

  // 表格列配置
  const columns: ColumnsType<AssetInfo> = [
    {
      title: '基础支撑平台',
      dataIndex: 'platform',
      key: 'platform',
      width: 150,
      render: () => '上海（SH）',
    },
    {
      title: '资源名称',
      dataIndex: 'assetName',
      key: 'assetName',
      width: 200,
    },
    {
      title: '资源编码',
      dataIndex: 'assetCode',
      key: 'assetCode',
      width: 150,
    },
    {
      title: '资源类型',
      dataIndex: 'assetType',
      key: 'assetType',
      width: 120,
      render: (type: string) => {
        const typeMap: Record<string, string> = {
          API: 'API接口',
          DATABASE: '数据库',
          FILE: '文件',
          STREAM: '流式数据',
        };
        return typeMap[type] || type;
      },
    },
    {
      title: '数据提供方',
      dataIndex: 'provider',
      key: 'provider',
      width: 150,
    },
    {
      title: '更新频率',
      dataIndex: 'updateFrequency',
      key: 'updateFrequency',
      width: 120,
    },
    {
      title: '数据量',
      dataIndex: 'dataSize',
      key: 'dataSize',
      width: 120,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const statusMap = {
          ONLINE: { text: '已上线', color: 'success' },
          OFFLINE: { text: '已下线', color: 'default' },
          MAINTAINING: { text: '维护中', color: 'warning' },
        };
        const { text, color } = statusMap[status as keyof typeof statusMap] || { text: status, color: 'default' };
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleView(record)}>
            查看
          </Button>
        </Space>
      ),
    },
  ];

  // 处理搜索
  const handleSearch = async (values: any) => {
    try {
      await fetchAssetsList({
        ...values,
        current: 1,
        size: pagination.pageSize,
      });
    } catch (error) {
      console.error('搜索失败:', error);
    }
  };

  // 处理重置
  const handleReset = () => {
    form.resetFields();
    fetchAssetsList({
      current: 1,
      size: pagination.pageSize,
    });
  };

  // 处理表格变化
  const handleTableChange = (pagination: any, filters: any, sorter: any) => {
    fetchAssetsList({
      current: pagination.current,
      size: pagination.pageSize,
      ...form.getFieldsValue(),
      ...filters,
    });
  };

  // 处理查看
  const handleView = (record: AssetInfo) => {
    navigate(`/global-info/resource-detail/${record.id}`);
  };

  return (
    <Card bordered={false}>
      <Form
        form={form}
        layout="inline"
        onFinish={handleSearch}
        style={{ marginBottom: 24 }}
      >
        <Form.Item name="assetName" label="资源名称">
          <Input placeholder="请输入资源名称" allowClear />
        </Form.Item>
        <Form.Item name="assetType" label="资源类型">
          <Select placeholder="请选择资源类型" allowClear style={{ width: 200 }}>
            <Option value="API">API接口</Option>
            <Option value="DATABASE">数据库</Option>
            <Option value="FILE">文件</Option>
            <Option value="STREAM">流式数据</Option>
          </Select>
        </Form.Item>
        <Form.Item name="status" label="状态">
          <Select placeholder="请选择状态" allowClear style={{ width: 150 }}>
            <Option value="ONLINE">已上线</Option>
            <Option value="OFFLINE">已下线</Option>
            <Option value="MAINTAINING">维护中</Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button onClick={handleReset}>重置</Button>
          </Space>
        </Form.Item>
      </Form>

      <Table<AssetInfo>
        columns={columns}
        dataSource={data}
        rowKey="id"
        pagination={pagination}
        loading={loading}
        onChange={handleTableChange}
      />
    </Card>
  );
};

export default AssetsList; 